#!/bin/sh
# ./install-service.sh

# 获取当前执行脚本文件所在目录 ${PRGDIR}
PRG="$0"
while [ -h "$PRG" ] ; do
  ls=`ls -ld "$PRG"`
  link=`expr "$ls" : '.*-> \(.*\)$'`
  if expr "$link" : '/.*' > /dev/null; then
    PRG="$link"
  else
    PRG=`dirname "$PRG"`/"$link"
  fi
done
PRGDIR=$(cd $(dirname $PRG); pwd)

if [ ! -n "${PRGDIR}" ]; then
  echo "script error, PRGDIR is error, exit!";
  exit -1;
fi

# 执行 ./${pkg.name}-boot.conf
SERVICE_CONF_FILE=${pkg.name}-boot.conf
if [ ! -f "${PRGDIR}/${SERVICE_CONF_FILE}" ]; then
  echo "${PRGDIR}/${SERVICE_CONF_FILE} is not exist, exit!";
  exit -1;
fi
. ${PRGDIR}/${SERVICE_CONF_FILE}

# 本应用执行用户身份设置
export USER_NAME=iboxpay
export GROUP_NAME=iboxpay

# create group and user
#getent group ${GROUP_NAME} >/dev/null || groupadd -r ${GROUP_NAME}
#getent passwd ${USER_NAME} >/dev/null || \
#useradd -d ${APP_DIR} -g ${GROUP_NAME} -M -r ${USER_NAME} -s /sbin/nologin >/dev/null 2>&1
#if [ $? -ne 0 ]; then
#  echo "Fail to create group or user, exit!"
#  exit -1;
#fi

cd ${APP_DIR}

# init directories
mkdir -p ${LOG_FOLDER}
mkdir -p ${LOG_FOLDER}/gc
mkdir -p ${PID_FOLDER}/${APP_NAME}

chown -R ${USER_NAME}:${GROUP_NAME} ${APP_DIR}
chmod a+rx `find ${APP_DIR} -type d`
chmod -R a+r ${APP_DIR}

chown -R ${USER_NAME}:${GROUP_NAME} ${LOG_FOLDER}
chmod a+rx `find ${LOG_FOLDER} -type d`

chown -R ${USER_NAME}:${GROUP_NAME} ${PID_FOLDER}/${APP_NAME}
chmod a+rx `find ${PID_FOLDER}/${APP_NAME} -type d`

chmod a+rx $JAR

# service setting
#ln -s -f $JAR /etc/init.d/${APP_NAME}
#chkconfig ${APP_NAME} on

# firewall setting
#iptables -I INPUT -p tcp --dport ${server.port} -j ACCEPT
#/etc/rc.d/init.d/iptables save
#iptables -L -n | grep :${server.port}

echo "execute \"/etc/init.d/${APP_NAME} start\" to start the application."
